﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using MxWeiXinPF.Common;

namespace MxWeiXinPF.Web.admin.order
{
    public partial class order_list_wxpay : MxWeiXinPF.Web.UI.ManagePage
    {
        protected MxWeiXinPF.Model.manager admin_info;
        protected int express_status;
        protected string keywords = string.Empty;
        protected int page;
        protected int pageSize;
        protected int payment_status;
        protected int status;
        protected int totalCount;
        protected string starttime;
        protected string endtime;
        protected int selectshopid;
        protected decimal sumamount = 0.0m;
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            base.ChkAdminLevel("order_list_wxpay", MXEnums.ActionEnum.Delete.ToString());
            int num = 0;
            int num2 = 0;
            MxWeiXinPF.BLL.orders orders = new MxWeiXinPF.BLL.orders();
            for (int i = 0; i < this.rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)this.rptList.Items[i].FindControl("hidId")).Value);
                CheckBox box = (CheckBox)this.rptList.Items[i].FindControl("chkId");
                if (box.Checked)
                {
                    if (orders.Delete(id))
                    {
                        num++;
                    }
                    else
                    {
                        num2++;
                    }
                }
            }
            base.AddAdminLog(MXEnums.ActionEnum.Delete.ToString(), string.Concat(new object[] { "删除订单成功", num, "条，失败", num2, "条" }));
            base.JscriptMsg(string.Concat(new object[] { "删除成功", num, "条，失败", num2, "条！" }), Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}", new string[] { this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords }), "Success");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.starttime = this.txtStart.Text.ToString();
            this.endtime = this.txtEnd.Text.ToString();
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&selectshopid={4}&start={5}&end={6}", new string[] { this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.txtKeywords.Text, this.selectshopid.ToString(), starttime, endtime }));
        }

        protected string CombSqlTxt(int _status, int _payment_status, int _express_status, string _keywords)
        {
            StringBuilder builder = new StringBuilder();
            if (_status > 0)
            {
                builder.Append(" and status=" + _status);
            }
            if (_payment_status > 0)
            {
                builder.Append(" and payment_status=" + _payment_status);
            }
            if (_express_status > 0)
            {
                builder.Append(" and express_status=" + _express_status);
            }
            builder.Append(" and payment_id=3 ");
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                builder.Append(" and (order_no like '%" + _keywords + "%' or user_name like '%" + _keywords + "%' or accept_name like '%" + _keywords + "%')");
            }
            if (this.selectshopid == 0) //店铺全选状态
            {
                Model.manager weixin = base.GetAdminInfo();
                if (weixin.agentLevel == 0)  //普通店铺
                {
                    int tempshopid = 0;
                    if (GetRelativeAdminInfo() != null)
                    {
                        tempshopid = GetRelativeAdminInfo().id;
                    }
                    else
                    {
                        tempshopid = GetAdminInfo().id;
                    }

                    if (weixin.id == 39 || tempshopid == 39) //管理员
                    {

                    }
                    else //普通店铺
                    {
                        builder.AppendFormat(" and shopid =" + tempshopid);
                    }
                }
                else //代理店铺
                {

                    builder.Append(" and shopid in (");
                    foreach (ListItem x in this.ddlShops.Items)
                    {
                        if (x.Value != "0")
                        {
                            builder.Append(x.Value);
                            builder.Append(",");
                        }
                    }
                    builder = builder.Remove(builder.Length - 1, 1);
                    builder.Append(") ");
                    // strTemp.AppendFormat(" shopid =" + selectshopid);
                }
            }
            else
            {
                builder.AppendFormat(" and shopid =" + selectshopid);
            }

            if (string.IsNullOrEmpty(starttime))
            {
                builder.AppendFormat(" and add_time >= '" + DateTime.Now.AddDays(-7).ToShortDateString() + "' ");
            }
            else
            {
                builder.AppendFormat(" and add_time >= '" + starttime + "' ");
            }
            if (string.IsNullOrEmpty(endtime))
            {
                builder.AppendFormat(" and add_time <= '" + DateTime.Now.AddDays(1).ToShortDateString() + "' ");
            }
            else
            {
                builder.AppendFormat(" and add_time <= '" + endtime + "' ");
            }
            return builder.ToString();
        }

        protected void ddlExpressStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&selectshopid={4}&start={5}&end={6}", new string[] { this.status.ToString(), this.payment_status.ToString(), this.ddlExpressStatus.SelectedValue, this.keywords, this.selectshopid.ToString(), starttime, endtime }));
        }

        protected void ddlPaymentStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&selectshopid={4}&start={5}&end={6}", new string[] { this.status.ToString(), this.ddlPaymentStatus.SelectedValue, this.express_status.ToString(), this.keywords, this.selectshopid.ToString(), starttime, endtime }));
        }

        protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&selectshopid={4}&start={5}&end={6}", new string[] { this.ddlStatus.SelectedValue, this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.selectshopid.ToString(), starttime, endtime }));
        }
        protected void ddlShops_SelectedIndexChanged(object sender, EventArgs e)
        {
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&selectshopid={2}&keywords={3}&selectshopid={4}&start={5}&end={6}",
                this.status.ToString(), this.payment_status.ToString(), ddlExpressStatus.SelectedValue, this.keywords, this.ddlShops.SelectedValue, starttime, endtime));
        }

        protected string GetOrderStatus(int _id, int status, int payment_status, int express_status)
        {
            string str = string.Empty;
            switch (status)
            {
                case 1:
                    if (payment_status <= 0)
                    {
                        return "待确认";
                    }
                    return "待付款";

                case 2:
                    if (express_status <= 1)
                    {
                        return "待发货";
                    }
                    return "已发货";

                case 3:
                    return "交易完成";

                case 4:
                    return "已取消";

                case 5:
                    return "已作废";
            }
            return str;
        }

        private int GetPageSize(int _default_size)
        {
            int num;
            if (int.TryParse(Utils.GetCookie("order_list_wxpay_page_size"), out num) && (num > 0))
            {
                return num;
            }
            return _default_size;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.status = MXRequest.GetQueryInt("status");
            this.payment_status = MXRequest.GetQueryInt("payment_status");
            this.express_status = MXRequest.GetQueryInt("express_status");
            this.keywords = MXRequest.GetQueryString("keywords");
            this.pageSize = this.GetPageSize(10);
            this.selectshopid = MXRequest.GetQueryInt("selectshopid");
            this.starttime = MXRequest.GetQueryString("start");
            this.endtime = MXRequest.GetQueryString("end");
            if (!this.Page.IsPostBack)
            {
                base.ChkAdminLevel("order_list_wxpay", MXEnums.ActionEnum.View.ToString());
                this.admin_info = base.GetAdminInfo();
                this.TreeBind();
                this.RptBind(" " + this.CombSqlTxt(this.status, this.payment_status, this.express_status, this.keywords), "add_time desc");

                if (string.IsNullOrEmpty(this.starttime))
                {
                    txtStart.Text = DateTime.Now.AddDays(-7).ToShortDateString();
                }
                else
                {
                    this.txtStart.Text = starttime;
                }
                if (string.IsNullOrEmpty(endtime))
                {
                    txtEnd.Text = DateTime.Now.ToShortDateString();
                }
                else
                {
                    this.txtEnd.Text = endtime;
                }
            }
        }

        private void RptBind(string _strWhere, string _orderby)
        {
            MxWeiXinPF.Model.manager weixin = base.GetAdminInfo();
            this.page = MXRequest.GetQueryInt("page", 1);
            if (this.status > 0)
            {
                this.ddlStatus.SelectedValue = this.status.ToString();
            }
            if (this.payment_status > 0)
            {
                this.ddlPaymentStatus.SelectedValue = this.payment_status.ToString();
            }
            if (this.express_status > 0)
            {
                this.ddlExpressStatus.SelectedValue = this.express_status.ToString();
            }
            this.txtKeywords.Text = this.keywords;
            BLL.orders bll = new BLL.orders();
            DataSet set = new DataSet();
            DataSet ds2 = new DataSet();
            if (weixin.agentLevel == 0)
            {
                if (weixin.id == 39)
                {
                    set = bll.GetListEx(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    ds2 = bll.GetListSum(_strWhere);
                }
                else
                {
                    set = bll.GetListEx(this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    ds2 = bll.GetListSum(_strWhere);
                }  
            }
            else
            {
                if (weixin.agentLevel == 1)
                {
                    set = bll.GetListByCounty(weixin.id, string.IsNullOrEmpty(weixin.county) ? 0 : int.Parse(weixin.county), this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    ds2 = bll.GetListByCountySum(0, string.IsNullOrEmpty(weixin.county) ? 0 : int.Parse(weixin.county), _strWhere);
                }
                else if (weixin.agentLevel == 2)
                {
                    set = bll.GetListByCity(weixin.id, string.IsNullOrEmpty(weixin.city) ? 0 : int.Parse(weixin.city), this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    ds2 = bll.GetListByCitySum(0, string.IsNullOrEmpty(weixin.city) ? 0 : int.Parse(weixin.city), _strWhere);
                }
                else if (weixin.agentLevel == 3)
                {
                    set = bll.GetListByProvince(weixin.id, string.IsNullOrEmpty(weixin.province) ? 0 : int.Parse(weixin.province), this.pageSize, this.page, _strWhere, _orderby, out this.totalCount);
                    ds2 = bll.GetListByProvinceSum(0, string.IsNullOrEmpty(weixin.province) ? 0 : int.Parse(weixin.province), _strWhere);
                }
                else
                {
                    return;
                }
            }

            if (((set != null) && (set.Tables.Count > 0)) && (set.Tables[0].Rows.Count > 0))
            {
                for (int i = 0; i < set.Tables[0].Rows.Count; i++)
                {
                    DataRow row = set.Tables[0].Rows[i];
                    row["statusName"] = this.GetOrderStatus(MyCommFun.Obj2Int(row["id"]), MyCommFun.Obj2Int(row["status"]), MyCommFun.Obj2Int(row["payment_status"]), MyCommFun.Obj2Int(row["express_status"]));
                }
            }
            this.rptList.DataSource = set;
            this.rptList.DataBind();
            this.txtPageNum.Text = this.pageSize.ToString();
            string linkUrl = Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&page={4}&selectshopid={5}&start={6}&end={7}", new string[] { this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, "__id__", this.selectshopid.ToString(), starttime, endtime });
            this.PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, linkUrl, 8);
            if (ds2 != null && ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
            {
                if (ds2.Tables[0].Rows[0][0] != null && ds2.Tables[0].Rows[0][0].ToString() != "")
                {
                    sumamount = Convert.ToDecimal(ds2.Tables[0].Rows[0][0].ToString());
                    this.lbSum.Text = sumamount.ToString() + "元";
                    return;
                }
            }
            this.lbSum.Text = sumamount.ToString() + "元";
        }

        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int num;
            if (int.TryParse(this.txtPageNum.Text.Trim(), out num) && (num > 0))
            {
                Utils.WriteCookie("order_list_wxpay_page_size", num.ToString(), 0x3840);
            }
            base.Response.Redirect(Utils.CombUrlTxt("order_list_wxpay.aspx", "status={0}&payment_status={1}&express_status={2}&keywords={3}&selectshopid={4}&start={5}&end={6}", new string[] { this.status.ToString(), this.payment_status.ToString(), this.express_status.ToString(), this.keywords, this.selectshopid.ToString(), starttime, endtime }));
        }

        private void TreeBind()
        {
            try
            {
                Model.manager weixin = base.GetAdminInfo();
                BLL.manager bll = new BLL.manager();
                DataSet ds = new DataSet();
                if (weixin.agentLevel == 0)
                {
                    if (weixin.id == 39)
                    {
                        ds = bll.GetList(-1, "", " id asc");
                    }
                    else
                    {
                        ds = bll.GetList(-1, " id = " + weixin.id + " ", " id asc");
                    }
                }
                else
                {
                    if (weixin.agentLevel == 1)
                    {
                        ds = bll.GetListByCounty(string.IsNullOrEmpty(weixin.county) ? 0 : int.Parse(weixin.county));
                    }
                    else if (weixin.agentLevel == 2)
                    {
                        ds = bll.GetListByCity(string.IsNullOrEmpty(weixin.city) ? 0 : int.Parse(weixin.city));
                    }
                    else if (weixin.agentLevel == 3)
                    {
                        ds = bll.GetListByProvince(string.IsNullOrEmpty(weixin.province) ? 0 : int.Parse(weixin.province));
                    }
                    else
                    {
                        return;
                    }
                }

                this.ddlShops.Items.Clear();
                this.ddlShops.Items.Add(new ListItem("所有店铺", "0"));
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ddlShops.Items.Add(new ListItem(ds.Tables[0].Rows[i]["real_name"].ToString(), ds.Tables[0].Rows[i]["id"].ToString()));

                    if (ds.Tables[0].Rows[i]["id"].ToString() == this.selectshopid.ToString())
                    {
                        this.ddlShops.SelectedValue = ds.Tables[0].Rows[i]["id"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public string GetShopName(int shopid)
        {
            Model.manager mm = new BLL.manager().GetModel(shopid);
            if (mm != null)
            {
                return mm.real_name;
            }
            return "";
        }

        protected string GetCouponInfo(string orderid)
        {
            string info = "未使用优惠券";
            BLL.wx_shop_coupon_data bcoupondata = new BLL.wx_shop_coupon_data();

            List<Model.wx_shop_coupon_data> datas = bcoupondata.GetModelList(string.Format(" ordersn={0} ", orderid));
            if (datas != null && datas.Count > 0)
            {
                Model.wx_shop_coupon_data mc = datas[0];
                Model.wx_shop_coupon mcoupon = new BLL.wx_shop_coupon().GetModel(mc.couponid);
                if (mcoupon != null)
                {
                    info = string.Format("面值:{0},描述:{1}", mcoupon.money, mcoupon.description);
                }
            }
            return info;
        }
    }
}